package com.qyx.pmpucat.controller;

import com.qyx.pmpucat.common.result.Result;
import com.qyx.pmpucat.common.result.Results;
import com.qyx.pmpucat.dto.QuestionDTO;
import com.qyx.pmpucat.entity.Question;
import com.qyx.pmpucat.service.QuestionService;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 问题控制器
 */
@RestController
@RequestMapping("/question")
@RequiredArgsConstructor
@Validated
public class QuestionController {

    private final QuestionService questionService;

    /**
     * 创建问题
     */
    @PostMapping("/create")
    public Result<Long> createQuestion(@RequestBody @Valid QuestionDTO questionDTO) {
        Long id = questionService.createQuestion(questionDTO);
        return Results.success(id);
    }

    /**
     * 更新问题
     */
    @PutMapping("/update")
    public Result<Void> updateQuestion(@RequestBody @Valid QuestionDTO questionDTO) {
        questionService.updateQuestion(questionDTO);
        return Results.success();
    }

    /**
     * 删除问题
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteQuestion(@PathVariable Long id) {
        questionService.deleteQuestion(id);
        return Results.success();
    }

    /**
     * 获取问题详情
     */
    @GetMapping("/{id}")
    public Result<Question> getQuestionDetail(@PathVariable Long id) {
        Question result = questionService.getQuestionDetail(id);
        return Results.success(result);
    }

    /**
     * 根据问卷ID获取问题列表
     */
    @GetMapping("/questionnaire/{questionnaireId}")
    public Result<List<Question>> getQuestionsByQuestionnaireId(@PathVariable Long questionnaireId) {
        List<Question> result = questionService.getQuestionsByQuestionnaireId(questionnaireId);
        return Results.success(result);
    }

    /**
     * 专业批量导入题目
     */
    @PostMapping("/importQuestion")
    public Result<String> importQuestion(@RequestParam("file") MultipartFile file,
                                         @RequestParam("questionnaireId") Long questionnaireId) {
        String result = questionService.importQuestion(file, questionnaireId);
        return Results.success(result);
    }

    /**
     * 导出问卷到Excel
     */
    @GetMapping("/export/{questionnaireId}")
    public ResponseEntity<byte[]> exportQuestion(@PathVariable Long questionnaireId, HttpServletResponse response) {

        return questionService.exportQuestionsToExcel(questionnaireId, response);
    }
} 